// https://www.lintcode.com/problem/search-insert-position/

public class Solution {
    /**
     * @param A: an integer sorted array
     * @param target: an integer to be inserted
     * @return: An integer
     */
    public int searchInsert(int[] A, int target) {
        // write your code here
        if (A.length > 0) {
            int start = 0, end = A.length, mid = -1;
            while (start < end) {
                mid = (start + end) / 2;
                if (A[mid] < target) {
                    start = mid + 1;
                }
                else if (A[mid] > target) {
                    end = mid;
                }
                else {
                    break;
                }
            }
            if (A[mid] > target) {
                return mid;
            }
            else if (A[mid] < target) {
                return mid + 1;
            }
            else {
                for (int i = mid -1; i >= 0; --i) {
                    if (A[i] < target) {
                        return i + 1;
                    }
                }
            }
        }
        return 0;
    }
}